package pers.whj.sort;

public class SelectionSort<T> extends Sort<T> {
    public SelectionSort(T[] data) throws SortException {
        super(data);
    }

    public SelectionSort(T[] data, Compare<T> compare) throws SortException {
        super(data, compare);
    }

    @Override
    public void sort(int left, int right) throws SortException {
        sort(mData, mCompare, left, right);
    }

    public static <E> void sort(E[] data) throws SortException {
        sort(data, null);
    }

    public static <E> void sort(E[] data, Compare<E> compare) throws SortException {
        sort(data, compare, 0, data == null ? 0 : data.length - 1);
    }

    public static <E> void sort(E[] data, Compare<E> compare, int left, int right) throws SortException {
        check(data, compare, left, right);
        if (right - left >= 1) {
            for (int i = left; i < right; i++) {
                int k = i;
                for (int j = i + 1; j <= right; j++) {
                    if (compare.swap(data[k], data[j])) {
                        k = j;
                    }
                }
                if (k != i) {
                    E temp = data[i];
                    data[i] = data[k];
                    data[k] = temp;
                }
            }
        }
    }
}